package com.jinzhi.sys.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.domain.DictDO;
import com.jinzhi.common.service.DictService;
import com.jinzhi.common.utils.ApiResult;
import com.jinzhi.common.utils.Result;
import com.jinzhi.common.utils.StringUtil;
import com.jinzhi.jzapi.msg.PackTemplateMap;
import com.jinzhi.jzapi.msg.WxPushServiceQcl;
import com.jinzhi.jzapi.msg.domain.TemplateData;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ExaminationCostExportVo;
import com.jinzhi.jzweb.pojo.ExaminationCostImportVo;
import com.jinzhi.jzweb.pojo.UserExportIntegralVO;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.SysUserRelevancyDO;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.sys.service.SysUserRelevancyService;
import com.jinzhi.sys.domain.RoleDO;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.domain.UserDetailDO;
import com.jinzhi.sys.domain.UserRoleDO;
import com.jinzhi.sys.service.RoleService;
import com.jinzhi.sys.service.UserRoleService;
import com.jinzhi.sys.service.UserService;
import com.jinzhi.sys.vo.UserVO;
import com.jinzhi.wxmp.domain.MpConfigDO;
import com.jinzhi.wxmp.service.MpConfigService;
import io.swagger.models.auth.In;
import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.collections.list.SynchronizedList;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <pre>
 * </pre>
 * <p>
 * <small> 2018年3月23日 | Aron</small>
 */
@RequestMapping("/sys/user")
@Controller
public class UserController extends BaseController {
    private String prefix = "sys/user";

    @Autowired
    private IntegralUserDetailService integralUserDetailService;
    @Autowired
    private CoursesService coursesService;
    @Autowired
    SysUserRelevancyService userRelevancyService;
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    UserRoleService userRoleService;
    @Autowired
    DictService dictService;
    @Autowired
    private MsgService msgService;
    @Autowired
    private OrganizationNewsService organizationNewsService;
    @Autowired
    private ExpertsService expertsService;
    @Autowired
    private MsgTemplateService msgTemplateService;
    @Autowired
    private WxPushServiceQcl wxPushServiceQcl;
    @Autowired
    private MpConfigService mpConfigService;

    @Autowired
    private BookOrderService bookOrderService;


    @Autowired
    private ExaminationCostService examinationCostService;

    @Autowired
    private JzUserCoursesRelationshipsService jzUserCoursesRelationshipsService;

    @Autowired
    private ZykResourcesUserRecordService zykResourcesUserRecordService;

    @Autowired
    private ZykResourcesChaptersService zykResourcesChaptersService;

    @Log("进入系统用户列表页面")
    @RequiresPermissions("sys:user:user")
    @GetMapping("")
    String user(Model model) {
        return prefix + "/user";
    }


    @Log("资源库用户列表页面入口")
    @RequiresPermissions("sys:fromUser:user")
    @GetMapping("getFromUser")
    String fromUser(Model model) {
        return "sys/resourceUser/user";
    }


    @Log("资源库用户新增页面入口")
    @RequiresPermissions("sys:fromUser:add")
    @GetMapping("fromUserAdd")
    String addFromUser(Model model) {
        model.addAttribute("organizationNews", organizationNewsService.selByOrgId());
        return "sys/resourceUser/add";
    }


    @Log("资源库用户修改页面入口")
    @RequiresPermissions("sys:fromUser:edit")
    @GetMapping("/fromUserEdit/{id}")
    String addUser(Model model, @PathVariable("id") Long id) {
        UserDetailDO userDetailDO = userService.getByUserDetailId(id);
        model.addAttribute("user", userDetailDO);
        Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().orderBy("name");
        model.addAttribute("organizationNews", organizationNewsService.selectList(orWrapper));
        return "sys/resourceUser/edit";
    }

    @RequiresPermissions("sys:user:edit")
    @Log("课程权限")
    @GetMapping("/accessConfiguration/{id}")
    String accessConfiguration(Model model, @PathVariable("id") Long id) {

        List<CoursesDO> coursesDOS = coursesService.selectList(null);


        UserDO userDO = userService.getByUserId(id);
        model.addAttribute("user", userDO);


        EntityWrapper<JzUserCoursesRelationshipsDO> wrapper = new EntityWrapper<>();
        wrapper.eq("user_id", id);
        List<JzUserCoursesRelationshipsDO> byUserAll = jzUserCoursesRelationshipsService.selectList(wrapper);

        if (byUserAll.size() < 1) {
            model.addAttribute("coursesAll", coursesDOS);
            return prefix + "/accessConfiguration";
        }


        for (int i = 0; i < byUserAll.size(); i++) {
            for (int j = 0; j < coursesDOS.size(); j++) {
                //如果課程id相同
                if (coursesDOS.get(j).getId().equals(byUserAll.get(i).getCoursesId())) {
                    coursesDOS.get(j).setIsShow("1");
                }
            }
        }

        model.addAttribute("coursesAll", coursesDOS);

        return prefix + "/accessConfiguration";
    }


    private String getUserDepartment(String userId) {
        String department = null;
        EntityWrapper<UserRoleDO> wrapper1 = new EntityWrapper<>();
        wrapper1.eq("userId", userId);
        Page<UserRoleDO> page1 = userRoleService.selectPage(getPages(UserRoleDO.class), wrapper1);
        for (UserRoleDO list : page1.getRecords()) {
            EntityWrapper<RoleDO> wrapper2 = new EntityWrapper<>();
            wrapper2.eq("id", list.getRoleId());
            wrapper2.like("roleName", "市场");
            //优先匹配市场人员权限
            List<RoleDO> roleDO = roleService.selectList(wrapper2);
            if (roleDO.size() > 0) {
                department = roleDO.get(0).getRoleName();
                break;
            }

        }
        if (StringUtil.notEmpty(department)) {
            return department;
        }
        return null;
    }


    private String getUserName(String userId) {
        UserDO userDO = userService.selectById(userId); //查询用户姓名
        return userDO.getName();
    }


    @Log("根据userId查询该账号教材")
    @GetMapping("/selBookOrderByUserId")
    @ResponseBody
    public Result<List<BookOrderDO>> selBookOrderByUserId(Long userId, String school, Integer year, String province, String city) {
        EntityWrapper<BookOrderDO> wrapper = new EntityWrapper();
        wrapper.eq("creare_user", userId);
        if (StringUtil.notEmpty(school) && school != null && school != "") {
            wrapper.like("school", school);
        }
        if (StringUtil.notEmpty(city) && city != null && city != "") {
            wrapper.like("city", city);
        }
        if (year != null) {
            wrapper.eq("year", year);
        }
        if (province != null && province != "" && StringUtils.isNotBlank(province)) {
            wrapper.like("province", province);
        }
        List<BookOrderDO> list = bookOrderService.selectList(wrapper);
        return Result.ok(list);
    }


    @Log("根据userId查询该账号考试费")
    @GetMapping("/selExaminationCostByUserId")
    @ResponseBody
    public Result<List<ExaminationCostDO>> selExaminationCostByUserId(Long userId, String school, Integer year, String province, String city) {

        EntityWrapper<ExaminationCostDO> wrapper = new EntityWrapper();
        wrapper.eq("region_user_id", userId);
        if (StringUtil.notEmpty(school) && school != null && school != "") {
            wrapper.like("org_name", school);
        }
        if (StringUtil.notEmpty(city) && city != null && city != "") {
            wrapper.like("city", city);
        }
        if (year != null) {
            wrapper.eq("year", year);
        }
        if (province != null && province != "" && StringUtils.isNotBlank(province)) {
            wrapper.like("province", province);
        }

        List<ExaminationCostDO> list = examinationCostService.selectList(wrapper);
        return Result.ok(list);
    }


    @Log("教材订单数据迁移")
    @PostMapping("/updBookOrderByUserId")
    @ResponseBody
    @Transactional
    public Result<Boolean> updBookOrderByUserId(@RequestBody Map<String, Object> request) {

        List<String> bookOrderIds = (List<String>) request.get("bookOrderIds");
        Long userId = Long.parseLong((String) request.get("userId"));

        List<Long> convertedBookOrderIds = bookOrderIds.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());

        List<BookOrderDO> bookOrderDOS = bookOrderService.selectBatchIds(convertedBookOrderIds);
        for (int i = 0; i < bookOrderDOS.size(); i++) {
            bookOrderDOS.get(i).setCreareUser(userId); //修改订单创建人员
            bookOrderDOS.get(i).setDepartment(getUserDepartment(String.valueOf(userId))); //获取部门
        }
        boolean b = bookOrderService.updateBatchById(bookOrderDOS);
        return Result.ok(b);
    }


    @Log("考试费订单数据迁移")
    @PostMapping("/updExaminationCostByUserId")
    @ResponseBody
    @Transactional
    public Result<Boolean> updExaminationCostByUserId(@RequestBody Map<String, Object> request) {

        List<String> bookOrderIds = (List<String>) request.get("bookOrderIds");
        Long userId = Long.parseLong((String) request.get("userId"));

        List<Long> convertedBookOrderIds = bookOrderIds.stream()
                .map(Long::parseLong)
                .collect(Collectors.toList());

        List<ExaminationCostDO> examinationCostDOS = examinationCostService.selectBatchIds(convertedBookOrderIds);

        for (int i = 0; i < examinationCostDOS.size(); i++) {
            examinationCostDOS.get(i).setRegionUserId(userId); //修改区域负责人id
            examinationCostDOS.get(i).setRegionDepartment(getUserDepartment(String.valueOf(userId))); //修改区域负责人部门
            examinationCostDOS.get(i).setRegionUserName(getUserName(String.valueOf(userId))); //用户姓名
        }
        boolean b = examinationCostService.updateBatchById(examinationCostDOS);
        return Result.ok(b);
    }


    @Log("教程订单迁移页面")
    @GetMapping("/migrationOrder/{id}")
    String migrationOrder(Model model, @PathVariable("id") Long id) {
        model.addAttribute("userId", id);
        return prefix + "/migrationOrder";
    }


//    @Log("考试费，劳务费，返费迁移页面")
//    @GetMapping("/migrationTestFee/{id}")
//    String migrationTestFee(Model model, @PathVariable("id") Long id) {
//        model.addAttribute("userId",id);
//        return prefix + "/migrationTestFee";
//    }


    @Log("查询系统用户列表")
    @GetMapping("/list")
    @ResponseBody
    public Result<Page<UserDO>> list(UserDO userDTO) {
        Wrapper<UserDO> wrapper = new EntityWrapper<UserDO>().orderBy("id", false);
        if (userDTO.getSex() != null) {
            wrapper.eq("sex", userDTO.getSex());
        }
        if (StringUtil.notEmpty(userDTO.getIdNumber())) {
            wrapper.eq("idNumber", userDTO.getIdNumber());
        }
        if (userDTO.getStatus() != null) {
            wrapper.eq("status", userDTO.getStatus());
        }
        if (userDTO.getType() != null) {
            wrapper.eq("type", userDTO.getType());
        }
        if (StringUtil.notEmpty(userDTO.getName())) {
            wrapper.like("name", userDTO.getName());
        }
        if (StringUtil.notEmpty(userDTO.getUsername())) {
            wrapper.like("username", userDTO.getUsername());
        }
        if (StringUtil.notEmpty(userDTO.getMobile())) {
            wrapper.like("mobile", userDTO.getMobile());
        }
        if (userDTO.getState() != null) {
            wrapper.eq("state", userDTO.getState());
        }
        if (userDTO.getType() != null) {
            wrapper.eq("type", userDTO.getType());
        }
        if (userDTO.getUserFrom() != null) {
            wrapper.eq("user_from", userDTO.getUserFrom());
        }
        if (StringUtils.isNotBlank(userDTO.getOrgName())) {
            Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().like("name", userDTO.getOrgName());
            List<OrganizationNewsDO> organizationNewsDOS = organizationNewsService.selectList(orWrapper);
            String str = "";
            for (OrganizationNewsDO organizationNewsDO : organizationNewsDOS) {
                str = str + organizationNewsDO.getId() + ",";
            }
            wrapper.and();
            if (StringUtils.isNotBlank(str)) {
                wrapper.in("orgId", str.substring(0, str.length() - 1));
            } else {
                wrapper.eq("orgId", null);
            }
        }
        Page<UserDO> pages = new Page<UserDO>(userDTO.getPageNumber(), userDTO.getPageSize());
        Page<UserDO> page = userService.selectPage(pages, wrapper);
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            UserDO obj = (UserDO) page.getRecords().get(i);
            if (obj.getOrgId() != null) {
                OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(obj.getOrgId());
                if (organizationNewsDO != null) {
                    obj.setOrgName(organizationNewsDO.getName());
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return Result.ok(page);
    }


    @Log("查询系统用户列表")
    @GetMapping("/marketUserList")
    @ResponseBody
    public Result<?> marketUserList() {
        Map map = new HashMap<String, Object>();
        map.put("name", "市场部");
        List<Map> mapList = new ArrayList<Map>();
        Map map1 = new HashMap<String, Object>();
        map1.put("name", "市场一部");
        Map map2 = new HashMap<String, Object>();
        map2.put("name", "市场二部");
        Long roleId1 = 1386577149715402754L;//市场一部角色ID,直接写死id,提高效率
        Long roleId2 = 1386577245253259266L;//市场二部角色ID
        List<UserRoleDO> userRoleDOS1 = userRoleService.findByKv("roleId", roleId1);
        List<UserRoleDO> userRoleDOS2 = userRoleService.findByKv("roleId", roleId2);
        List<UserDO> userDOS1 = new ArrayList<UserDO>();
        List<UserDO> userDOS2 = new ArrayList<UserDO>();
        List<Map> userMapList1 = new ArrayList<Map>();
        List<Map> userMapList2 = new ArrayList<Map>();
        for (UserRoleDO userRoleDO : userRoleDOS1) {
            Map userMap = new HashMap<String, String>();
            userMap.put("name", userService.getByUserId(userRoleDO.getUserId()).getName());
            userMapList1.add(userMap);
        }
        for (UserRoleDO userRoleDO : userRoleDOS2) {
            Map userMap = new HashMap<String, String>();
            userMap.put("name", userService.getByUserId(userRoleDO.getUserId()).getName());
            userMapList2.add(userMap);
        }
        map1.put("children", userMapList1);
        map2.put("children", userMapList2);
        mapList.add(map1);
        mapList.add(map2);
        map.put("children", mapList);
        return Result.ok(map);
    }


    @RequiresPermissions("sys:user:add")
    @Log("添加用户")
    @GetMapping("/add")
    String add(Model model) {
        List<RoleDO> roles = roleService.selectList(null);
        model.addAttribute("roles", roles);
        model.addAttribute("organizationNews", organizationNewsService.selByOrgId());
        return prefix + "/add";
    }

    /**
     * @description: 用户管理编辑功能
     * @author: YangQiWu
     * @date: 2023/3/22 15:11
     * @param: [model, id：用户id]
     * @return: java.lang.String
     **/
    @RequiresPermissions("sys:user:edit")
    @Log("编辑用户")
    @GetMapping("/edit/{id}")
    String edit(Model model, @PathVariable("id") Long id) {
        UserDetailDO userDetailDO = userService.getByUserDetailId(id);
        model.addAttribute("user", userDetailDO);
        List<RoleDO> roles = roleService.findListStatusByUserId(id);
        model.addAttribute("roles", roles);
        Wrapper<OrganizationNewsDO> orWrapper = new EntityWrapper<OrganizationNewsDO>().orderBy("name");
        model.addAttribute("organizationNews", organizationNewsService.selectList(orWrapper));
        return prefix + "/edit";
    }

    /**
     * @description: 用户管理预览详情页面
     * @author: YangQiWu
     * @date: 2023/3/22 15:08
     * @param: [id：用户id, model]
     * @return: java.lang.String
     **/
    @GetMapping("/info/{id}")
    @RequiresPermissions("sys:user:user")
    String info(@PathVariable("id") Long id, Model model) {
        UserDetailDO userDetailDO = userService.getByUserDetailId(id);
        if (userDetailDO.getDateOfBirth() == null || userDetailDO.getDateOfBirth().equals("")) {
            userDetailDO.setDateOfBirth(null);
        }
        model.addAttribute("user", userDetailDO);
        return prefix + "/info";
    }


    /**
     * @description: 用户资源管理预览详情页面
     **/
    @GetMapping("/fromInfo/{id}")
    String fromInfo(@PathVariable("id") Long id, Model model) {
        UserDetailDO userDetailDO = userService.getByUserDetailId(id);
        if (userDetailDO.getDateOfBirth() == null || userDetailDO.getDateOfBirth().equals("")) {
            userDetailDO.setDateOfBirth(null);
        }
        model.addAttribute("user", userDetailDO);
        return "sys/resourceUser/info";
    }


    /**
     * 查询用户 “新员工培训” 学习记录
     *
     * @param id
     * @return
     */
    @GetMapping("/userRecord")
    @ResponseBody
    Result<?> userRecord(ZykResourcesUserRecordDO zykResourcesUserRecordDTO) {
        Map map = new HashMap();
        Wrapper<ZykResourcesUserRecordDO> wrapper = new EntityWrapper<ZykResourcesUserRecordDO>().eq("user_id", zykResourcesUserRecordDTO.getId()).orderBy("creater_date", false);
        Page<ZykResourcesUserRecordDO> pageList = zykResourcesUserRecordService.selectPage(getPages(ZykResourcesUserRecordDO.class), wrapper);
        List<ZykResourcesUserRecordDO> records = pageList.getRecords();
        records.forEach(a -> {
            a.setTime(convertSecondsToTimeUnits(Long.valueOf(a.getDurationTime())));
            //查询课程名称
            Long resourcesChaptersId = a.getResourcesChaptersId();
            ZykResourcesChaptersDO zykResourcesChaptersDO = zykResourcesChaptersService.selectById(resourcesChaptersId);
            if (null != zykResourcesChaptersDO) {
                a.setResourcesName(zykResourcesChaptersDO.getName());
            }
        });
        pageList.setRecords(records);
        map.put("pageList", pageList);
        Map map2 = new HashMap();
        map2.put("userId", zykResourcesUserRecordDTO.getId());
        Long l = zykResourcesUserRecordService.selRecordNum(map2);
        //查询用户学习总时长
        map.put("timeAll", convertSecondsToTimeUnits(l));

        return Result.ok(map);
    }

    public static String convertSecondsToTimeUnits(Long seconds) {
        if (seconds == null || seconds < 0) {
            return "0";
        }

        int hours = (int) (seconds / 3600);
        int remainingSecondsAfterHours = (int) (seconds % 3600);
        int minutes = remainingSecondsAfterHours / 60;
        int secondsLeft = remainingSecondsAfterHours % 60;

        if (hours > 0) {
            return (hours + "小时 " + minutes + "分钟 " + secondsLeft + "秒");
        } else if (minutes > 0) {
            return (minutes + "分钟 " + secondsLeft + "秒");
        } else {
            return (secondsLeft + "秒");
        }
    }

    /**
     * @description: 添加用户
     * @author: YangQiWu
     * @date: 2023/3/30 9:14
     * @param: [user：用户详情对象]
     * @return: com.jinzhi.common.utils.Result<java.lang.String>
     **/
    @RequiresPermissions("sys:user:add")
    @Log("保存用户")
    @PostMapping("/save")
    @ResponseBody
    Result<String> save(UserDetailDO user) {
        user.setState(3);
        user.setGmtCreate(new DateTime());
        user.setCreateTime(new DateTime().toTimestamp());
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
        if (organizationNewsDO != null) {
            user.setOrgName(organizationNewsDO.getName());
        }

        UserDO userDO = new UserDO();
        SysUserRelevancyDO userRelevancyDO = new SysUserRelevancyDO();
        //获取用户表相关属性
        userDO.setId(user.getId());
        userDO.setUsername(user.getUsername());
        userDO.setSalt(user.getSalt());
        userDO.setName(user.getName());
        userDO.setPassword(user.getPassword());
        userDO.setEmail(user.getEmail());
        userDO.setMobile(user.getMobile());
        userDO.setStatus(user.getStatus());
        userDO.setUserIdCreate(user.getUserIdCreate());
        userDO.setGmtCreate(user.getGmtCreate());
        userDO.setGmtModified(user.getGmtModified());
        userDO.setSex(user.getSex());
        userDO.setPicId(user.getPicId());
        userDO.setLiveAddress(user.getLiveAddress());
        userDO.setHobby(user.getHobby());
        userDO.setProvince(user.getProvince());
        userDO.setCity(user.getCity());
        userDO.setDistrict(user.getDistrict());
        userDO.setCerOpenId(user.getCerOpenId());
        userDO.setIdNumber(user.getIdNumber());
        userDO.setPayPassword(user.getPayPassword());
        userDO.setType(user.getType());
        userDO.setOrgId(user.getOrgId());
        userDO.setOrgName(user.getOrgName());
        userDO.setMoney(user.getMoney());
        userDO.setWxId(user.getWxId());
        userDO.setHeadPortrait(user.getHeadPortrait());
        userDO.setDateOfBirth(user.getDateOfBirth());
        userDO.setNation(user.getNation());
        userDO.setEducation(user.getEducation());
        userDO.setMajor(user.getMajor());
        userDO.setPoliticalAffiliation(user.getPoliticalAffiliation());
        userDO.setOfficialCapacity(user.getOfficialCapacity());
        userDO.setQQ(user.getQQ());
        userDO.setExperience(user.getExperience());
        userDO.setTraOpenId(user.getTraOpenId());
        userDO.setRemark(user.getRemark());
        userDO.setState(user.getState());
        userDO.setLastEdit(user.getLastEdit());
        userDO.setLoginWxCode(user.getLoginWxCode());
        userDO.setOfficialCapacityName(user.getOfficialCapacityName());
        userDO.setIntegral(user.getIntegral());
        userDO.setRegionProvinceId(user.getRegionProvinceId());
        userDO.setRegionCityId(user.getRegionCityId());
        userDO.setInviterId(user.getInviterId());
        userDO.setInviteeId(user.getInviteeId());
        userDO.setroleIds(user.getRoleIds());
        userDO.setHeadPortrait(user.getImg());
        //获取用户子表相关属性
        userRelevancyDO.setTimeOfEnrollment(user.getTimeOfEnrollment());
        userRelevancyDO.setType(user.getUserType());
        userRelevancyDO.setSchool(user.getSchool());
        userRelevancyDO.setSchoolAddress(user.getSchoolAddress());
        userRelevancyDO.setSchoolIndetailAddress(user.getSchoolIndetailAddress());
        userRelevancyDO.setSchoolLevel(user.getSchoolLevel());
        userRelevancyDO.setRatingCertificate(user.getRatingCertificate());
        userRelevancyDO.setDepartment(user.getDepartment());
        userRelevancyDO.setImg(user.getImg());
        userRelevancyDO.setShippingAddress(user.getShippingAddress());
        userRelevancyDO.setShippingIndetailAddress(user.getShippingIndetailAddress());
        userRelevancyDO.setDutyParagraph(user.getDutyParagraph());
        userRelevancyDO.setOrgName(user.getTicketOrgName());
        userRelevancyDO.setCardNumber(user.getCardNumber());
        userRelevancyDO.setAccountName(user.getAccountName());
        userRelevancyDO.setBank(user.getBank());
        userRelevancyDO.setCreateTime(user.getCreateTime());
        userRelevancyDO.setUpdateTime(user.getUpdateTime());

        //添加用户扩展
        userRelevancyService.insert(userRelevancyDO);

        userDO.setUserRelevancyId(userRelevancyDO.getId().toString());
        //添加用户
        userService.insert(userDO);

        return Result.ok();
    }

    @Log("资源库迁入已存在用户用户")
    @PostMapping("/transformUser")
    @ResponseBody
    public Result transformUser(UserDetailDO user) {
        UserDO userDO = new UserDO();
        BeanUtils.copyProperties(user, userDO);
        userDO.setType(1);
        userDO.setUserFrom(1);
        boolean b = userService.updateById(userDO);
        return Result.ok();
    }


    /**
     * @description: 添加用户
     * @author: YangQiWu
     * @date: 2023/3/30 9:14
     * @param: [user：用户详情对象]
     * @return: com.jinzhi.common.utils.Result<java.lang.String>
     **/
    @Log("资源库保存用户")
    @PostMapping("/fromSave")
    @ResponseBody
    Result<Object> fromSave(UserDetailDO user) {

        // 手机号唯一
        EntityWrapper<UserDO> usernameWrapper = new EntityWrapper<>();
        usernameWrapper.eq("mobile", user.getMobile());
        UserDO existUser = userService.selectOne(usernameWrapper);
        if (Objects.nonNull(existUser)) {
            if (ObjectUtil.isEmpty(existUser.getName())) {
                existUser.setName(existUser.getUsername());
            }
            return Result.ok(existUser);
        }
        // 用户名唯一
        EntityWrapper<UserDO> wrapper = new EntityWrapper<>();
        wrapper.eq("username", user.getUsername());
        UserDO existUser2 = userService.selectOne(usernameWrapper);
        if (Objects.nonNull(existUser2)) {
            return Result.ok("用户名已存在！");
        }


        user.setState(3);
        user.setGmtCreate(new DateTime());
        user.setCreateTime(new DateTime().toTimestamp());
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
        if (organizationNewsDO != null) {
            user.setOrgName(organizationNewsDO.getName());
        }

        UserDO userDO = new UserDO();
        SysUserRelevancyDO userRelevancyDO = new SysUserRelevancyDO();
        if (!StringUtil.notEmpty(user.getName())) {
            user.setName(user.getUsername());
        }
        //获取用户表相关属性
        userDO.setUserFrom(user.getUserFrom());
        userDO.setId(user.getId());
        userDO.setUsername(user.getUsername());
        userDO.setSalt(user.getSalt());
        userDO.setName(user.getName());
        userDO.setPassword(user.getPassword());
        userDO.setEmail(user.getEmail());
        userDO.setMobile(user.getMobile());
        userDO.setStatus(user.getStatus());
        userDO.setUserIdCreate(user.getUserIdCreate());
        userDO.setGmtCreate(user.getGmtCreate());
        userDO.setGmtModified(user.getGmtModified());
        userDO.setSex(user.getSex());
        userDO.setPicId(user.getPicId());
        userDO.setLiveAddress(user.getLiveAddress());
        userDO.setHobby(user.getHobby());
        userDO.setProvince(user.getProvince());
        userDO.setCity(user.getCity());
        userDO.setDistrict(user.getDistrict());
        userDO.setCerOpenId(user.getCerOpenId());
        userDO.setIdNumber(user.getIdNumber());
        userDO.setPayPassword(user.getPayPassword());
        userDO.setType(user.getType());
        userDO.setOrgId(user.getOrgId());
        userDO.setOrgName(user.getOrgName());
        userDO.setMoney(user.getMoney());
        userDO.setWxId(user.getWxId());
        userDO.setHeadPortrait(user.getHeadPortrait());
        userDO.setDateOfBirth(user.getDateOfBirth());
        userDO.setNation(user.getNation());
        userDO.setEducation(user.getEducation());
        userDO.setMajor(user.getMajor());
        userDO.setPoliticalAffiliation(user.getPoliticalAffiliation());
        userDO.setOfficialCapacity(user.getOfficialCapacity());
        userDO.setQQ(user.getQQ());
        userDO.setExperience(user.getExperience());
        userDO.setTraOpenId(user.getTraOpenId());
        userDO.setRemark(user.getRemark());
        userDO.setState(user.getState());
        userDO.setLastEdit(user.getLastEdit());
        userDO.setLoginWxCode(user.getLoginWxCode());
        userDO.setOfficialCapacityName(user.getOfficialCapacityName());
        userDO.setIntegral(user.getIntegral());
        userDO.setRegionProvinceId(user.getRegionProvinceId());
        userDO.setRegionCityId(user.getRegionCityId());
        userDO.setInviterId(user.getInviterId());
        userDO.setInviteeId(user.getInviteeId());
        userDO.setroleIds(user.getRoleIds());
        userDO.setHeadPortrait(user.getImg());
        //获取用户子表相关属性
        userRelevancyDO.setTimeOfEnrollment(user.getTimeOfEnrollment());
        userRelevancyDO.setType(user.getUserType());
        userRelevancyDO.setSchool(user.getSchool());
        userRelevancyDO.setSchoolAddress(user.getSchoolAddress());
        userRelevancyDO.setSchoolIndetailAddress(user.getSchoolIndetailAddress());
        userRelevancyDO.setSchoolLevel(user.getSchoolLevel());
        userRelevancyDO.setRatingCertificate(user.getRatingCertificate());
        userRelevancyDO.setDepartment(user.getDepartment());
        userRelevancyDO.setImg(user.getImg());
        userRelevancyDO.setShippingAddress(user.getShippingAddress());
        userRelevancyDO.setShippingIndetailAddress(user.getShippingIndetailAddress());
        userRelevancyDO.setDutyParagraph(user.getDutyParagraph());
        userRelevancyDO.setOrgName(user.getTicketOrgName());
        userRelevancyDO.setCardNumber(user.getCardNumber());
        userRelevancyDO.setAccountName(user.getAccountName());
        userRelevancyDO.setBank(user.getBank());
        userRelevancyDO.setCreateTime(user.getCreateTime());
        userRelevancyDO.setUpdateTime(user.getUpdateTime());

        //添加用户扩展
        userRelevancyService.insert(userRelevancyDO);

        userDO.setUserRelevancyId(userRelevancyDO.getId().toString());
        //添加用户
        userService.insert(userDO);

        return Result.ok();
    }


    /**
     * @description: 编辑用户保存更新
     * @author: YangQiWu
     * @date: 2023/3/30 9:16
     * @param: [user：用户详情对象]
     * @return: com.jinzhi.common.utils.Result<java.lang.String>
     **/
    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/update")
    @ResponseBody
    Result<String> update(UserDetailDO user) {
        UserDetailDO userDetailDO = userService.getByUserDetailId(user.getId());
        UserDO userDO = new UserDO();
        SysUserRelevancyDO userRelevancyDO = new SysUserRelevancyDO();
        user.setGmtModified(new DateTime());
        user.setUpdateTime(new DateTime().toTimestamp());

        //获取用户表相关属性
        userDO.setId(user.getId());
        userDO.setUsername(user.getUsername());
        userDO.setSalt(user.getSalt());
        userDO.setName(user.getName());
        userDO.setPassword(user.getPassword());
        userDO.setEmail(user.getEmail());
        userDO.setMobile(user.getMobile());
        userDO.setStatus(user.getStatus());
        userDO.setUserIdCreate(user.getUserIdCreate());
        userDO.setGmtCreate(user.getGmtCreate());
        userDO.setGmtModified(user.getGmtModified());
        userDO.setSex(user.getSex());
        userDO.setPicId(user.getPicId());
        userDO.setLiveAddress(user.getLiveAddress());
        userDO.setHobby(user.getHobby());
        userDO.setProvince(user.getProvince());
        userDO.setCity(user.getCity());
        userDO.setDistrict(user.getDistrict());
        userDO.setCerOpenId(user.getCerOpenId());
        userDO.setIdNumber(user.getIdNumber());
        userDO.setPayPassword(user.getPayPassword());
        userDO.setType(user.getType());
        userDO.setOrgId(user.getOrgId());
        userDO.setOrgName(user.getOrgName());
        userDO.setMoney(user.getMoney());
        userDO.setWxId(user.getWxId());
        userDO.setHeadPortrait(user.getHeadPortrait());
        userDO.setDateOfBirth(user.getDateOfBirth());
        userDO.setNation(user.getNation());
        userDO.setEducation(user.getEducation());
        userDO.setMajor(user.getMajor());
        userDO.setPoliticalAffiliation(user.getPoliticalAffiliation());
        userDO.setOfficialCapacity(user.getOfficialCapacity());
        userDO.setQQ(user.getQQ());
        userDO.setExperience(user.getExperience());
        userDO.setTraOpenId(user.getTraOpenId());
        userDO.setRemark(user.getRemark());
        userDO.setState(user.getState());
        userDO.setLastEdit(user.getLastEdit());
        userDO.setLoginWxCode(user.getLoginWxCode());
        userDO.setOfficialCapacityName(user.getOfficialCapacityName());
        userDO.setIntegral(user.getIntegral());
        userDO.setRegionProvinceId(user.getRegionProvinceId());
        userDO.setRegionCityId(user.getRegionCityId());
        userDO.setInviterId(user.getInviterId());
        userDO.setInviteeId(user.getInviteeId());
        userDO.setroleIds(user.getRoleIds());
        if (user.getImg() != null) {
            userDO.setHeadPortrait(user.getImg());
        }

        //获取用户子表相关属性
        userRelevancyDO.setId(userDetailDO.getUserRelevancyId());
        userRelevancyDO.setTimeOfEnrollment(user.getTimeOfEnrollment());
        userRelevancyDO.setType(user.getUserType());
        userRelevancyDO.setSchool(user.getSchool());
        userRelevancyDO.setSchoolAddress(user.getSchoolAddress());
        userRelevancyDO.setSchoolIndetailAddress(user.getSchoolIndetailAddress());
        userRelevancyDO.setSchoolLevel(user.getSchoolLevel());
        userRelevancyDO.setRatingCertificate(user.getRatingCertificate());
        userRelevancyDO.setDepartment(user.getDepartment());
        userRelevancyDO.setImg(user.getImg());
        userRelevancyDO.setShippingAddress(user.getShippingAddress());
        userRelevancyDO.setShippingIndetailAddress(user.getShippingIndetailAddress());
        userRelevancyDO.setDutyParagraph(user.getDutyParagraph());
        userRelevancyDO.setOrgName(user.getTicketOrgName());
        userRelevancyDO.setCardNumber(user.getCardNumber());
        userRelevancyDO.setAccountName(user.getAccountName());
        userRelevancyDO.setBank(user.getBank());
        userRelevancyDO.setCreateTime(user.getCreateTime());
        userRelevancyDO.setUpdateTime(user.getUpdateTime());


        //同时更新专家表的所属机构id
        List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id", user.getId());
        if (expertsDOS != null && expertsDOS.size() > 0) {
            List<ExpertsDO> expertsDOS1 = new ArrayList<>();
            for (ExpertsDO expertsDO : expertsDOS) {
                //if(user.getOrgId() != null){
                //  if(expertsDO.getOrgId() != null){
                if (!expertsDO.getOrgId().equals(user.getOrgId())) {
                    expertsDO.setOrgId(user.getOrgId());
                    expertsDOS1.add(expertsDO);
                } else {
                    expertsDO.setOrgId(user.getOrgId());
                    expertsDOS1.add(expertsDO);
                }
                //  }
            }

            if (expertsDOS1.size() > 0) {
                expertsService.updateBatchById(expertsDOS1, expertsDOS1.size());
            }
        }
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
        if (organizationNewsDO != null) {
            user.setOrgName(organizationNewsDO.getName());
        } else {
            user.setOrgName(null);
            user.setOrgId(null);
            userService.updayeOrg(userDO);
        }

        //更新用户表
        userService.updateById(userDO);
        //更新用户扩展表
        userRelevancyService.updateById(userRelevancyDO);

        return Result.ok();
    }


    @Log("资源库更新用户")
    @PostMapping("/fromUpdate")
    @ResponseBody
    Result<String> fromUpdate(UserDetailDO user) {
        UserDetailDO userDetailDO = userService.getByUserDetailId(user.getId());
        UserDO userDO = new UserDO();
        SysUserRelevancyDO userRelevancyDO = new SysUserRelevancyDO();
        user.setGmtModified(new DateTime());
        user.setUpdateTime(new DateTime().toTimestamp());

        //获取用户表相关属性
        userDO.setUserFrom(user.getUserFrom());
        userDO.setId(user.getId());
        userDO.setUsername(user.getUsername());
        userDO.setSalt(user.getSalt());
        userDO.setName(user.getName());
        userDO.setPassword(user.getPassword());
        userDO.setEmail(user.getEmail());
        userDO.setMobile(user.getMobile());
        userDO.setStatus(user.getStatus());
        userDO.setUserIdCreate(user.getUserIdCreate());
        userDO.setGmtCreate(user.getGmtCreate());
        userDO.setGmtModified(user.getGmtModified());
        userDO.setSex(user.getSex());
        userDO.setPicId(user.getPicId());
        userDO.setLiveAddress(user.getLiveAddress());
        userDO.setHobby(user.getHobby());
        userDO.setProvince(user.getProvince());
        userDO.setCity(user.getCity());
        userDO.setDistrict(user.getDistrict());
        userDO.setCerOpenId(user.getCerOpenId());
        userDO.setIdNumber(user.getIdNumber());
        userDO.setPayPassword(user.getPayPassword());
        userDO.setType(user.getType());
        userDO.setOrgId(user.getOrgId());
        userDO.setOrgName(user.getOrgName());
        userDO.setMoney(user.getMoney());
        userDO.setWxId(user.getWxId());
        userDO.setHeadPortrait(user.getHeadPortrait());
        userDO.setDateOfBirth(user.getDateOfBirth());
        userDO.setNation(user.getNation());
        userDO.setEducation(user.getEducation());
        userDO.setMajor(user.getMajor());
        userDO.setPoliticalAffiliation(user.getPoliticalAffiliation());
        userDO.setOfficialCapacity(user.getOfficialCapacity());
        userDO.setQQ(user.getQQ());
        userDO.setExperience(user.getExperience());
        userDO.setTraOpenId(user.getTraOpenId());
        userDO.setRemark(user.getRemark());
        userDO.setState(user.getState());
        userDO.setLastEdit(user.getLastEdit());
        userDO.setLoginWxCode(user.getLoginWxCode());
        userDO.setOfficialCapacityName(user.getOfficialCapacityName());
        userDO.setIntegral(user.getIntegral());
        userDO.setRegionProvinceId(user.getRegionProvinceId());
        userDO.setRegionCityId(user.getRegionCityId());
        userDO.setInviterId(user.getInviterId());
        userDO.setInviteeId(user.getInviteeId());
        userDO.setroleIds(user.getRoleIds());
        if (user.getImg() != null) {
            userDO.setHeadPortrait(user.getImg());
        }

        //获取用户子表相关属性
        userRelevancyDO.setId(userDetailDO.getUserRelevancyId());
        userRelevancyDO.setTimeOfEnrollment(user.getTimeOfEnrollment());
        userRelevancyDO.setType(user.getUserType());
        userRelevancyDO.setSchool(user.getSchool());
        userRelevancyDO.setSchoolAddress(user.getSchoolAddress());
        userRelevancyDO.setSchoolIndetailAddress(user.getSchoolIndetailAddress());
        userRelevancyDO.setSchoolLevel(user.getSchoolLevel());
        userRelevancyDO.setRatingCertificate(user.getRatingCertificate());
        userRelevancyDO.setDepartment(user.getDepartment());
        userRelevancyDO.setImg(user.getImg());
        userRelevancyDO.setShippingAddress(user.getShippingAddress());
        userRelevancyDO.setShippingIndetailAddress(user.getShippingIndetailAddress());
        userRelevancyDO.setDutyParagraph(user.getDutyParagraph());
        userRelevancyDO.setOrgName(user.getTicketOrgName());
        userRelevancyDO.setCardNumber(user.getCardNumber());
        userRelevancyDO.setAccountName(user.getAccountName());
        userRelevancyDO.setBank(user.getBank());
        userRelevancyDO.setCreateTime(user.getCreateTime());
        userRelevancyDO.setUpdateTime(user.getUpdateTime());


        //同时更新专家表的所属机构id
        List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id", user.getId());
        if (expertsDOS != null && expertsDOS.size() > 0) {
            List<ExpertsDO> expertsDOS1 = new ArrayList<>();
            for (ExpertsDO expertsDO : expertsDOS) {
                //if(user.getOrgId() != null){
                //  if(expertsDO.getOrgId() != null){
                if (!expertsDO.getOrgId().equals(user.getOrgId())) {
                    expertsDO.setOrgId(user.getOrgId());
                    expertsDOS1.add(expertsDO);
                } else {
                    expertsDO.setOrgId(user.getOrgId());
                    expertsDOS1.add(expertsDO);
                }
                //  }
            }

            if (expertsDOS1.size() > 0) {
                expertsService.updateBatchById(expertsDOS1, expertsDOS1.size());
            }
        }
        OrganizationNewsDO organizationNewsDO = organizationNewsService.selectById(user.getOrgId());
        if (organizationNewsDO != null) {
            user.setOrgName(organizationNewsDO.getName());
        } else {
            user.setOrgName(null);
            user.setOrgId(null);
            userService.updayeOrg(userDO);
        }

        //更新用户表
        userService.updateById(userDO);
        //更新用户扩展表
        userRelevancyService.updateById(userRelevancyDO);

        return Result.ok();
    }


    @RequiresPermissions("sys:user:edit")
    @Log("更新用户")
    @PostMapping("/updatePeronal")
    @ResponseBody
    Result<String> updatePeronal(UserDO user) {
        userService.updatePersonal(user);
        return Result.ok();
    }

    @RequiresPermissions("sys:user:remove")
    @Log("删除用户")
    @PostMapping("/remove")
    @ResponseBody
    @Transactional
    public Result<String> remove(Long id) {
        boolean b = userService.deleteById(id);
        if (b) {
            List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id", id);
            if (expertsDOS != null && expertsDOS.size() > 0) {
                List<Long> ids = new ArrayList<>();
                for (ExpertsDO expertsDO : expertsDOS) {
                    ids.add(expertsDO.getId());
                }
                boolean cc = expertsService.deleteBatchIds(ids);
                if (cc) {
                    return Result.ok();
                } else {
                    return Result.fail();
                }
            }
            return Result.ok();
        } else {
            return Result.fail();
        }
    }

    @RequiresPermissions("sys:user:batchRemove")
    @Log("批量删除用户")
    @PostMapping("/batchRemove")
    @ResponseBody
    @Transactional
    Result<String> batchRemove(@RequestParam("ids[]") Long[] userIds) {
        boolean b = userService.deleteBatchIds(Arrays.asList(userIds));
        if (b) {
            boolean ccd = true;
            for (Long id : userIds) {
                List<ExpertsDO> expertsDOS = expertsService.findByKv("user_id", id);
                if (expertsDOS != null && expertsDOS.size() > 0) {
                    List<Long> ids = new ArrayList<>();
                    for (ExpertsDO expertsDO : expertsDOS) {
                        ids.add(expertsDO.getId());
                    }
                    ccd = expertsService.deleteBatchIds(ids);
                }
            }
            if (ccd) {
                return Result.ok();
            } else {
                return Result.fail();
            }
        } else {
            return Result.fail();
        }
    }

    @PostMapping("/exist")
    @ResponseBody
    boolean exist(@RequestParam Map<String, Object> params) {
        // 存在，不通过，false
        return !userService.exist(params);
    }

    @RequiresPermissions("sys:user:resetPwd")
    @GetMapping("/resetPwd/{id}")
    String resetPwd(@PathVariable("id") Long userId, Model model) {
        UserDO userDO = new UserDO();
        userDO.setId(userId);
        model.addAttribute("user", userDO);
        return prefix + "/reset_pwd";
    }

    @Log("提交更改用户密码")
    @PostMapping("/resetPwd")
    @ResponseBody
    Result<?> resetPwd(UserVO userVO) {
        return userService.resetPwd(userVO, getUser());
    }

    @RequiresPermissions("sys:user:resetPwd")
    @Log("admin提交更改用户密码")
    @PostMapping("/adminResetPwd")
    @ResponseBody
    Result<String> adminResetPwd(UserVO userVO) {
        userService.adminResetPwd(userVO);
        return Result.ok();

    }

//    @RequiresPermissions("sys:user:add")
//    @Log("审核")
//    @PostMapping("/review")
//    @ResponseBody
//    Result<String> check(@RequestParam("ids[]") Long[] ids,Integer state  ,String remark) {
//
//        //查询字典:消息模板
//        DictDO dic = null;
//        String valStr = "";
//        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//        if (state == 2){
//            dic = dictService.findOneByKv("type" , "check_no_pass");
//            valStr = dic.getValue().replace("{value4}" , remark);
//        }else{
//            dic = dictService.findOneByKv("type" , "check_pass");
//            valStr = dic.getValue();
//        }
//        valStr =  valStr.replace("{value1}" , "个人信息");
//        valStr = valStr.replace("{value2}" , this.getUser().getUsername());
//        valStr = valStr.replace("{value3}" , formatter.format(new Date()));
//
//        for (Long id : ids){
//            UserDO user = userService.getByUserId(id);
//            user.setState(state);
//
//            MsgDO msg = new MsgDO();
//            if (state == 1){
//                msg.setTitle("您的个人信息审核通过！");
//                user.setRemark("");
//            }else {
//                msg.setTitle("您的个人信息审核未通过！");
//                user.setRemark(remark);
//            }
//            msg.setContent(valStr);
//            msg.setCreaterId(this.getUserId());
//            msg.setCreaterDate(new Date());
//            msg.setType(1);
//            msg.setMsgType(0);
//            msg.setUserId(id);
//            msg.setState(0);
//            if (userService.updateById(user)){
//                msgService.insert(msg);
//
//                //------------------------订阅消息模块-----------------------------\
//                MsgTemplateDO msgTemplate = msgTemplateService.findOneByKv("type" , 0, "temp_ip" ,user.getLastEdit());
////                UserDO user = userService.selectById(expertsDO.getUserId());
//                if (user.getCerOpenId() != null || user.getTraOpenId() != null){
//                    if (msgTemplate != null){
//                        String[] value = null;
//                        if (state == 1){//通过
//                            MsgTemplateDO templateDO = msgTemplateService.findOneByKv("pid" , msgTemplate.getId() , "type" , 2, "temp_ip" ,user.getLastEdit());
//                            value = templateDO.getContent().split("/n");
//                            for (int a = 0; a < value.length; a++){
//                                value[a] = value[a].replace("{value1}" ,"个人信息");
//                                value[a] = value[a].replace("{value2}" ,"个人信息");
//                                value[a] = value[a].replace("{date}" , formatter.format(new Date()));
//                            }
//                        }else if (state == 2){//未通过
//                            MsgTemplateDO templateDO = msgTemplateService.findOneByKv("pid" , msgTemplate.getId() , "type" , 3 ,"temp_ip" ,user.getLastEdit());
//                            value = templateDO.getContent().split("/n");
//                            for (int a = 0; a < value.length; a++){
//                                value[a] = value[a].replace("{value1}" ,"个人信息");
//                                value[a] = value[a].replace("{value2}" ,"个人信息");
//                                value[a] = value[a].replace("{remark}" ,remark);
//                                value[a] = value[a].replace("{date}" , formatter.format(new Date()));
//                            }
//                        }
//                        String[] parm = msgTemplate.getContent().split(",");
//                        Map<String, TemplateData> map = PackTemplateMap.get1(value , parm);
//
//                        MpConfigDO mc = mpConfigService.selectById(user.getLastEdit());
//                        if (user.getLastEdit() == 101){
//                            wxPushServiceQcl.sendMsgToUser(mc.getId().intValue() ,user.getCerOpenId(),msgTemplate.getCode(),map ,"pages/userInfo/userInfo");
//                        }else {
//                            wxPushServiceQcl.sendMsgToUser(mc.getId().intValue() ,user.getTraOpenId(),msgTemplate.getCode(),map ,"pages/userInfo/userInfo");
//                        }
//
//
//                    }
//                }
//                //------------------------订阅消息模块结束-----------------------------\
//
//            }
//
//        }
//        return Result.ok();
//    }
//


    @RequiresPermissions("sys:user:add")
    @Log("审核")
    @PostMapping("/review")
    @ResponseBody
    Result<String> check(@RequestParam("ids[]") Long[] ids, Integer state, String remark) {
        List<UserDO> userDOS = userService.selectBatchIds(Arrays.asList(ids));
        for (int i = 0; i < userDOS.size(); i++) {
            if (state == 1) {
                userDOS.get(i).setRemark("后台审核通过");
                userDOS.get(i).setState(1);
            } else if (state == 2) {
                userDOS.get(i).setRemark(remark);
                userDOS.get(i).setState(2);
            }
        }
        userService.updateBatchById(userDOS);
        return Result.ok();
    }


//
//    @RequiresPermissions("sys:user:add")
//    @Log("审核")
//    @PostMapping("/review")
//    @ResponseBody
//    @Transactional
//    Result<String> check(@RequestParam("ids[]") Long[] ids,Integer state  ,String remark) {
//        List<UserDO> userDOS = userService.selectBatchIds(Arrays.asList(ids));
//        List<IntegralUserDetailDO> list =new ArrayList<>();  //积分修改记录表
//
//        for (int i=0;i<userDOS.size();i++){
//            if (state == 1){
//                userDOS.get(i).setRemark("后台审核通过");
//                userDOS.get(i).setState(1);
//                if (userDOS.get(i).getIntegral() == null||"".equals(userDOS.get(i).getIntegral())){
//                    userDOS.get(i).setIntegral("0");
//                }
//                Integer sum = Integer.valueOf(userDOS.get(i).getIntegral()) + 3000;
//                userDOS.get(i).setIntegral(sum.toString());
//                IntegralUserDetailDO integralUserDetail = new IntegralUserDetailDO();
//                integralUserDetail.setIntegralDetail("+3000"); //扣除积分
//                integralUserDetail.setUserId(Long.valueOf(userDOS.get(i).getId())); //用户id
//                integralUserDetail.setIntegralGainDate(new Date()); //积分获取时间
//                integralUserDetail.setIntegralGainPathway("完善个人资料");
//                list.add(integralUserDetail);
//            }else if (state == 2){
//                userDOS.get(i).setRemark(remark);
//                userDOS.get(i).setState(2);
//            }
//        }
//        integralUserDetailService.insertBatch(list);
//        userService.updateBatchById(userDOS);
//        return Result.ok();
//    }
//
//
//


    @GetMapping("/treeView")
    String treeView() {
        return prefix + "/userTree";
    }

    @GetMapping("/personal")
    String personal(Model model) {
        UserDO userDO = userService.getByUserId(getUserId());
        model.addAttribute("user", userDO);
        List<DictDO> hobbyList = dictService.getHobbyList(userDO);
        model.addAttribute("hobbyList", hobbyList);
        List<DictDO> sexList = dictService.getSexList();
        model.addAttribute("sexList", sexList);
        return prefix + "/personal";
    }

    @GetMapping("/adminMessage")
    String adminMessage(Model model, String state) {
        model.addAttribute("state", state);
        return prefix + "/adminMessage";
    }

    @Log("上传头像")
    @ResponseBody
    @PostMapping("/uploadImg")
    Result<?> uploadImg(@RequestParam("avatar_file") MultipartFile file, String avatar_data, HttpServletRequest request)
            throws Exception {
        Map<String, Object> result = new HashMap<>();
        result = userService.updatePersonalImg(file, avatar_data, getUserId());
        return Result.ok(result);
    }


    @Log("消息中心列表")
    @GetMapping("/msgList")
    @ResponseBody
    Result<?> msgList(int current, int number, String state, String type) {
        UserDO user = this.getUser();
        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("state", state);
        map.put("type", type);
        Page<MsgDO> page = msgService.selMsgPage(current, number, map);
        List<MsgDO> list = page.getRecords();
        for (MsgDO msg : list) {
            msg.setUserName(user.getUsername());
            UserDO user1 = userService.getByUserId(msg.getCreaterId());
            msg.setCreaterName(user1.getUsername());
        }
        page.setRecords(list);
        return Result.ok(page);
    }


    @Log("消息中心更改状态")
    @GetMapping("/updateState")
    @ResponseBody
    Result<?> updateState(Long id) {
        MsgDO msg = msgService.selectById(id);
        msg.setState(2);
        msgService.updateById(msg);
        return Result.ok();
    }


    @Log("未读消息条数")
    @GetMapping("/unreadNum")
    @ResponseBody
    Result<?> unreadNum(String type) {
        if (getUser() != null) {
            List<MsgDO> msg = msgService.findByKv("state", 0, "userId", this.getUserId(), "type", type);
            return Result.ok(msg.size());
        } else {
            return Result.ok(0);
        }

    }

    @Log("导出用户积分")
    @PostMapping("/exportUserList")
    @Transactional
    @ResponseBody
    public Result<?> exportUserList(HttpServletResponse response, @RequestParam("file") MultipartFile file) {

        //---------------------------------检测导入信息及条件-----------------------------------------
        //第一步--判断文件格式
        if (!"application/vnd.ms-excel".equals(file.getContentType())) {
            return Result.fail("文件格式错误，请选择.xls文件");
        }

        //第二步--解析文件获得数据
        List<UserExportIntegralVO> list = EasyPoiUtil.importExcel(file, 0, 1, UserExportIntegralVO.class);
        System.out.println("解析的最后一条数据为：" + list.get(list.size() - 1).toString());
        if (list.size() == 0) {
            return Result.fail("Excel数据为空，请完善");
        }
        //提取电话的集合
        List<String> phoneList = list.stream().map(UserExportIntegralVO::getPhone).collect(Collectors.toList());
        //提取身份证的集合
        List<String> idNumberList = list.stream().map(UserExportIntegralVO::getIdNumber).collect(Collectors.toList());
        List<UserExportIntegralVO> list1 = new ArrayList<>();

//        List<UserDO> user1 = userService.selectList(new EntityWrapper<UserDO>().in("mobile",phoneList));
//        List<UserDO> user2 = userService.selectList(new EntityWrapper<UserDO>().in("idNumber",idNumberList));
//        List<UserDO> userDOS = new ArrayList<>();
//        if(!user1.isEmpty() && !user2.isEmpty()){
//            user1.forEach(a -> user2.forEach(b->{
//                if(Objects.equals(a.getId(),b.getId())){
//                    userDOS.add(a);
//                }
//            }));
//        }


//        List<UserDO> user1 = userService.selectList(new EntityWrapper<UserDO>().in("mobile", phoneList));
//        List<UserDO> user2 = userService.selectList(new EntityWrapper<UserDO>().in("idNumber", idNumberList));
//        List<UserDO> userDOS = new ArrayList<>();
//        // 设置批量处理大小（可根据实际情况调整）
//        int batchSize = 1000;
//        //收集user2的id，用于防止数据丢失
//        Set<Long> user2Ids = user2.stream().map(UserDO::getId).collect(Collectors.toSet());
//        //解决数据丢失
//        if (!user1.isEmpty()) {
//            for (int i = 0; i < user1.size(); i += batchSize) {
//                int endIndex = Math.min(i + batchSize, user1.size());
//                List<UserDO> batchUser1 = user1.subList(i, endIndex);
//                batchUser1.forEach(a -> {
//                    if (user2Ids.contains(a.getId())) {
//                        userDOS.add(a);
//                    }
//                });
//            }
//        }
        List<UserDO> userDOS = userService.selectListByPhoneAndIdNumber(phoneList, idNumberList);

        for (UserDO userDO : userDOS) {
            for (UserExportIntegralVO u : list) {
                if (u.getPhone().equals(userDO.getMobile())) {
                    UserExportIntegralVO vo = new UserExportIntegralVO();
                    if (userDO.getIntegral() != null) {
                        vo.setIntegral(userDO.getIntegral());
                    } else {
                        vo.setIntegral("0");
                    }
                    vo.setResume(u.getResume());
                    vo.setProvince(u.getProvince());
                    vo.setName(userDO.getName());
                    vo.setReason(u.getReason());
                    vo.setAwards(u.getAwards());
                    vo.setPublicStatus(u.getPublicStatus());
                    vo.setPhone(userDO.getMobile());
                    if (userDO.getRemark() != null) {
                        vo.setRemark(userDO.getRemark());
                    } else {
                        vo.setRemark("");
                    }
                    vo.setIdNumber(userDO.getIdNumber());
                    vo.setOrgName(userDO.getOrgName());
                    list1.add(vo);
                }
            }
        }
        EasyPoiUtil.exportExcel(list1, "优秀评选数据表", "优秀评选数据表", UserExportIntegralVO.class, "优秀评选数据表", response);
        return Result.ok("成功导出" + list1.size() + "条数据");
    }

}
